package com.itheima.filter;

import com.itheima.bean.Employee;
import com.itheima.bean.User;
import com.itheima.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();

        if (uri.contains("login") || uri.contains("api") || uri.contains("images") || uri.contains("js") || uri.contains("styles")
                || uri.contains("plugins")||uri.contains("user")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        Employee employee =(Employee) request.getSession().getAttribute("employee");
        User user = (User)request.getSession().getAttribute("user");
        if(employee!=null){
            //在这里保存员工的id到ThreadLocal里面去
            BaseContext.setCurrentId(employee.getId());
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        else if(employee==null&&user==null) {
            if(uri.contains("/front"))
                response.sendRedirect("/front/page/login.html");
            else
            response.sendRedirect("/backend/page/login/login.html");

        }
        if(user!=null){
            log.info("用户已登录，用户id为：" +request.getSession().getAttribute("user"));

            Long id = user.getId();
            BaseContext.setCurrentId(id);
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }




    }}


